<?php
namespace pay\WxpayAPI;
use \Exception;

class WeEncryption {
    public function __construct($key,$sslcert,$sslkey)
    {
        $this->sslcert_path = $sslcert;//退款证书路径（正式）
        $this->sslkey_path  = $sslkey;//退款证书密钥(正式)
        $this->key      = $key;       //商户Key
    }


    /**
     * 统一下单 网页（二维码）
     */

    public function GetPayUrl($data)
    {
        if($data['trade_type'] == "NATIVE")
        {
            $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            return self::WeChatCommonFunction($data,$url);
        }
        return false;
    }


    /**
     * 申请退款
     */
    public function refund($data){
        $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        //检测必填参数
        if(!array_key_exists('out_trade_no', $data) && !!array_key_exists('transaction_id', $data)) {
            throw new Exception("退款申请接口中，out_trade_no、transaction_id至少填一个！");
        }else if(!array_key_exists('out_refund_no', $data)){
            throw new Exception("退款申请接口中，缺少必填参数out_refund_no！");
        }else if(!array_key_exists('total_fee', $data)){
            throw new Exception("退款申请接口中，缺少必填参数total_fee！");
        }else if(!array_key_exists('refund_fee', $data)){
            throw new Exception("退款申请接口中，缺少必填参数refund_fee！");
        }
        return self::WeChatCommonFunction($data,$url);
    }

    public function refundQuery($data){
        $url = "https://api.mch.weixin.qq.com/pay/refundquery";
        return self::WeChatCommonFunction($data,$url);
    }




















    /**
     * 公共请求方法
     */
    public function WeChatCommonFunction($data,$url,$timeOut = 6){
        $data['sign'] = self::GetSign($data); //获取MD5签名
        $xml = self::ToXml($data); //数组转xml
        $response = self::postXmlCurl($xml,$url,true,$timeOut);
        $result = self::Init($response);
        return $result;
    }

    /**
     * 将xml转为array
     */
    public static function Init($response)
    {
        if(!$response){
            throw new Exception("xml数据异常！");
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $res = json_decode(json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $res;
    }



    /**
     * 以post方式提交xml到对应的接口url
     *
     * @param WxPayConfigInterface $config  配置对象
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second   url执行超时时间，默认30s
     * @throws Exception
     */
    private function postXmlCurl($xml, $url , $useCert = false)
    {
        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL, $url);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch,CURLOPT_ENCODING,"");

        if($useCert == true){
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            //证书文件请放入服务器的非web目录下
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $this->sslcert_path);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $this->sslkey_path);
        }

        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验

        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new Exception("curl出错，错误码:$error");
        }
    }

    /**
     * 设置签名，详见签名生成算法
     * @param string $value
     **/
    public function GetSign($data)
    {
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = self::ToUrlParams($data);
        //签名步骤二：在string后加入KEY
        $string = md5($string . "&key=".$this->key);
        //签名步骤四：所有字符转为大写
        $sign = strtoupper($string);
        return $sign;
    }


    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($data)
    {
        $buff = "";
        foreach ($data as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 输出xml字符
     * @throws Exception
     **/
    public function ToXml($data = [])
    {
        $xml = "<xml>";
        foreach ($data as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

}